<template>
    <div class="container-fluid">
        <div class="row">
            <div class="col">
                <breadcrumb v-bind:paths="paths" v-bind:name="name"></breadcrumb>
            </div>
        </div>
        <el-row>
           <el-col :span="12">

            <el-button type="primary" @click="uploadimg = !uploadimg" >选择图片</el-button> 
            <el-button  type="success" @click="submitUpload" :disabled="!uploadimg" >上传图片</el-button> 
            <el-button @click="gitosslist">刷新图片列表</el-button> 
            </el-col>
            <el-col :span="12">
              <i  class="el-icon-warning text-warning"  circle></i> 选择图片库 &nbsp;
              <el-select v-model="value" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-col>
        </el-row>
        <div class="row">
            <div class="col">
                 <transition name="el-fade-in-linear">
                <el-upload v-show="uploadimg" accept="image/*"  class="upload-demo" ref="upload" drag :file-list="fileList"  :auto-upload="false" action="https://jsonplaceholder.typicode.com/posts/" :http-request="putimg" :on-success="successUpload"  multiple>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击选择文件</em></div>
                    <div slot="tip" class="el-upload__tip">只能上传图片文件，如果上传的名称相同就会覆盖原文件</div>
                </el-upload>
                 </transition> 
            </div>
        </div>
        <hr>
        <div class="row" >
            <div class="col" >
                <h3>图片列表</h3>
                <el-table
                    :data="imglist"
                    height="500"
                    style="width: 100%">
                    <el-table-column
                        prop="name"
                        label="目录/名称"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="url"
                        label="路径"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="url"
                        label="图片"
                        width="80"
                        >
                        <template slot-scope="scope">
                            <img :src="stylename(scope.row.url)" alt="">
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="address"
                        label="删除"
                        width="180">
                         <template slot-scope="scope">
                            <el-button @click="delectClick(scope.row)" type="text" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                    </el-table>
            </div>
        </div>
    </div>
</template>

<script>
import OSS from "ali-oss";
import { asyncuploadAccess } from "../../plugins/api.js";
import breadcrumb from "@/components/breadcrumb.vue";
export default {
  name: "oss",
  data() {
    return {
      paths: [],
      name: "图片管理",
      fileList: [],
      imglist: [],
      uploadimg: false,
      value: "lessons-baner/",
      options: [
        {
          value: "lessons-baner/",
          label: "课程展示图片库"
        },
        {
          value: "videoImg/",
          label: "视频回答问题图片库"
        }
      ]
    };
  },
  mounted() {
    //this.gitosslist();
    this.start();
  },
  watch: {
    value() {
      this.start();
    }
  },
  methods: {
    stylename(name) {
      return `${name}?x-oss-process=style/style-50`;
    },
    async start() {
      this.gitosslist();
    },
    submitUpload() {
      let name;
      for (let v of this.options) {
        if (v.value === this.value) {
          name = v.label;
        }
      }
      this.$confirm(`此次将提交到${name}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$refs.upload.submit();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    async delectClick(i) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            let option = await this.getcreds();
            let client = new OSS(option);
            await client.delete(i.name);
            this.gitosslist();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          } catch (e) {
            this.$message({
              type: "info",
              message: "删除失败"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async gitosslist() {
      try {
        let option = await this.getcreds();
        let client = new OSS(option);
        let list = await client.list({
          "max-keys": 100,
          prefix: this.value
        });
        console.log(list.objects);
        this.imglist = [];
        let len = this.value.length;
        for (let v of list.objects) {
          if (v.name.length != len) {
            this.imglist.push({
              name: v.name,
              url: v.url
            });
          }
        }
      } catch (err) {
        console.log(err);
      }
    },
    async putimg(e) {
      if (this.uploadimg) {
        try {
          let option = await this.getcreds();
          let client = new OSS(option);
          // object表示上传到OSS的名字，可自己定义
          // file浏览器中需要上传的文件，支持HTML5 file 和 Blob类型
          let r1 = await client.put(`${this.value}${e.file.name}`, e.file);
          console.log(r1);
        } catch (e) {
          console.error("error: %j", e);
        }
      }
    },
    async getcreds() {
      let creds = await asyncuploadAccess();
      return {
        region: "oss-cn-beijing",
        bucket: "hterobot-image",
        stsToken: creds.securityToken,
        accessKeyId: creds.accessKeyId,
        accessKeySecret: creds.accessKeySecret
      };
    },
    successUpload(e) {
      console.log(e);
    }
  },
  components: {
    breadcrumb
  }
};
</script>

<style scoped>
.upload-demo {
  height: 450px;
  overflow-y: scroll;
  padding: 35px;
}
</style>